"""
翻译API控制器
提供邮件翻译功能
"""
from fastapi import APIRouter, Depends, Query, BackgroundTasks
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import Optional, List

from api.database import get_db
from api.model.user import User
from api.model.email_account import EmailAccount
from api.model.email import Email
from api.model.translation_config import TranslationConfig
from api.schemas.translation import TranslationConfigCreate, TranslationConfigUpdate, TranslationConfigResponse
from api.controller.auth import get_current_user
from api.utils.response import success, fail
from api.utils.async_helper import run_in_executor
from api.service.translation_service import translation_service
from api.service.email_service import EmailService
from api.utils.logger import get_logger

# 初始化日志
logger = get_logger("translate")

router = APIRouter()


@router.post("/email-accounts/{account_id}/emails/{email_id}/translate")
async def translate_email(
    account_id: int,
    email_id: int,
    force_translate: bool = Query(False, description="是否跳过缓存强制重新翻译"),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    全文翻译邮件内容和标题
    
    Args:
        account_id: 邮箱账户ID
        email_id: 邮件ID
        force_translate: 是否跳过缓存强制重新翻译
        current_user: 当前用户
        db: 数据库会话
        
    Returns:
        翻译后的HTML内容和标题
    """
    try:
        # 验证账户权限
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        
        if not account:
            return fail("邮箱账户未找到")
        
        # 查询邮件记录
        email_record = db.query(Email).filter(
            Email.id == email_id,
            Email.email_account_id == account_id
        ).first()
        
        if not email_record:
            return fail("邮件未找到")
        
        # 获取邮件HTML内容
        email_service = EmailService(account=account)
        
        # 步骤1：异步获取邮件内容（IMAP操作）
        def fetch_content_task():
            return email_service.fetch_email_content_on_demand(db, email_record)
        
        try:
            text_body, html_body, inline_images = await run_in_executor(fetch_content_task, timeout=60.0)
            
            # 确定要翻译的内容
            if html_body:
                content_to_translate = html_body
            elif text_body and text_body.strip().startswith('<!'):
                # text_body 看起来像是 HTML
                content_to_translate = text_body
            else:
                # 纯文本，转换为HTML
                content_to_translate = text_body.replace("\n", "<br>") if text_body else ""
            
            if not content_to_translate:
                return fail("邮件内容为空，无法翻译")
            
            # 步骤2：异步执行翻译（API调用，已在translation_service内部使用线程池）
            def translate_task():
                return translation_service.translate_email_content(
                    user_id=current_user.id,
                    db=db,
                    email_id=email_id,
                    html_content=content_to_translate,
                    subject=email_record.subject,  # 传递邮件标题
                    eml_path=email_record.eml_path,  # 传递EML文件路径
                    force_translate=force_translate  # 传递强制翻译参数
                )
            
            # 翻译可能需要更长时间（多次API调用），使用120秒超时
            translation_result = await run_in_executor(translate_task, timeout=120.0)
            
            if translation_result == "NO_DEFAULT_CONFIG":
                return fail("请先设置一个默认的翻译服务")
            
            if not translation_result:
                return fail("翻译服务暂时不可用，请检查您的翻译配置或稍后重试")
            
            # 获取翻译后的内容和标题
            translated_content = translation_result.get("content", "")
            translated_title = translation_result.get("title", email_record.subject)
            
            # 处理内嵌图片（如果有）
            if html_body and inline_images:
                import base64
                for cid, image in inline_images.items():
                    b64_data = base64.b64encode(image["data"]).decode('utf-8')
                    data_uri = f"data:{image['type']};base64,{b64_data}"
                    translated_content = translated_content.replace(f"cid:{cid}", data_uri)
            
            # 为所有链接添加 target="_blank" 属性
            from api.utils.helpers import add_target_blank_to_links
            translated_content = add_target_blank_to_links(translated_content)
            
            logger.info(f"邮件翻译成功 - email_id: {email_id}, user_id: {current_user.id}")
            
            return success({
                "content": translated_content,
                "title": translated_title,
                "email_id": email_id
            })
            
        except Exception as e:
            logger.error(f"获取邮件内容失败: {e}", exc_info=True)
            return fail(f"获取邮件内容失败: {str(e)}")
        
    except Exception as e:
        logger.error(f"翻译邮件失败: {e}", exc_info=True)
        return fail(f"翻译失败: {str(e)}")


# --- 翻译配置管理 ---

@router.get("/translation-configs", response_model=dict)
async def get_translation_configs(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的所有翻译配置（包括自己的和别人共享的）"""
    try:
        # 获取自己的配置和别人共享的配置
        configs = db.query(TranslationConfig).filter(
            (TranslationConfig.user_id == current_user.id) | (TranslationConfig.is_shared == True)
        ).order_by(TranslationConfig.id.desc()).all()
        
        # 获取当前用户的默认配置ID
        user = db.query(User).filter(User.id == current_user.id).first()
        default_config_id = user.default_translation_config_id if user else None
        
        config_list = []
        for c in configs:
            config_dict = TranslationConfigResponse.from_orm(c).dict()
            # 标记是否为默认配置
            config_dict['is_default'] = (c.id == default_config_id)
            
            # 判断是否为本人的配置
            is_own = c.user_id == current_user.id
            
            # 如果不是本人的配置，移除敏感的credentials信息
            if not is_own:
                config_dict['credentials'] = {}
            
            config_list.append(config_dict)
        
        return success(config_list)
    except Exception as e:
        logger.error(f"获取翻译配置列表失败: {e}", exc_info=True)
        return fail("获取翻译配置列表失败")

@router.post("/translation-configs", response_model=dict)
async def create_translation_config(
    config: TranslationConfigCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的翻译配置"""
    try:
        # 检查名称是否重复
        existing = db.query(TranslationConfig).filter(
            TranslationConfig.user_id == current_user.id,
            TranslationConfig.name == config.name
        ).first()
        if existing:
            return fail("配置名称已存在")
        
        # 验证AI翻译的提示词
        if config.provider == "ai":
            prompt = config.credentials.get("prompt", "")
            if prompt and prompt.strip():
                # 如果填写了提示词，必须包含必需的变量
                if "{text_json}" not in prompt:
                    return fail("自定义提示词必须包含变量 {text_json}")
                if "{target_language}" not in prompt:
                    return fail("自定义提示词必须包含变量 {target_language}")
        
        db_config = TranslationConfig(
            user_id=current_user.id,
            **config.dict()
        )
        db.add(db_config)
        db.commit()
        db.refresh(db_config)
        
        return success(TranslationConfigResponse.from_orm(db_config), msg="翻译配置添加成功")
    except Exception as e:
        db.rollback()
        logger.error(f"创建翻译配置失败: {e}", exc_info=True)
        return fail(f"创建翻译配置失败: {str(e)}")

@router.put("/translation-configs/{config_id}", response_model=dict)
async def update_translation_config(
    config_id: int,
    config_update: TranslationConfigUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新翻译配置"""
    try:
        db_config = db.query(TranslationConfig).filter(
            TranslationConfig.id == config_id
        ).first()
        
        if not db_config:
            return fail("配置不存在")
        
        # 检查权限：只能修改自己的配置
        if db_config.user_id != current_user.id:
            return fail("无权修改他人共享的配置")
        
        # 检查名称是否重复
        if config_update.name and config_update.name != db_config.name:
            existing = db.query(TranslationConfig).filter(
                TranslationConfig.user_id == current_user.id,
                TranslationConfig.name == config_update.name,
                TranslationConfig.id != config_id
            ).first()
            if existing:
                return fail("配置名称已存在")

        # 验证AI翻译的提示词
        if config_update.provider == "ai" or (not config_update.provider and db_config.provider == "ai"):
            # 获取更新后的credentials
            credentials = config_update.credentials if config_update.credentials else db_config.credentials
            prompt = credentials.get("prompt", "")
            if prompt and prompt.strip():
                # 如果填写了提示词，必须包含必需的变量
                if "{text_json}" not in prompt:
                    return fail("自定义提示词必须包含变量 {text_json}")
                if "{target_language}" not in prompt:
                    return fail("自定义提示词必须包含变量 {target_language}")

        update_data = config_update.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(db_config, field, value)
        
        db.commit()
        db.refresh(db_config)
        
        return success(TranslationConfigResponse.from_orm(db_config), msg="翻译配置更新成功")
    except Exception as e:
        db.rollback()
        logger.error(f"更新翻译配置失败: {e}", exc_info=True)
        return fail(f"更新翻译配置失败: {str(e)}")

@router.delete("/translation-configs/{config_id}", response_model=dict)
async def delete_translation_config(
    config_id: int,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除翻译配置"""
    try:
        db_config = db.query(TranslationConfig).filter(
            TranslationConfig.id == config_id
        ).first()
        
        if not db_config:
            return fail("配置不存在")
        
        # 检查权限：只能删除自己的配置
        if db_config.user_id != current_user.id:
            return fail("无权删除他人共享的配置")
        
        # 如果有其他用户将此配置设为默认，清除他们的默认配置
        db.query(User).filter(User.default_translation_config_id == config_id).update(
            {"default_translation_config_id": None}
        )
        
        db.delete(db_config)
        db.commit()
        
        # 定义一个在后台运行的任务来清理缓存文件
        def delete_cache_in_background(conf_id: int):
            from api.database import SessionLocal
            db_session = SessionLocal()
            try:
                logger.info(f"后台任务开始：为配置 {conf_id} 清理翻译缓存")
                translation_service.delete_translation_cache_for_config(conf_id, db_session)
                logger.info(f"后台任务结束：为配置 {conf_id} 清理翻译缓存")
            finally:
                db_session.close()

        # 将任务添加到后台任务队列
        background_tasks.add_task(delete_cache_in_background, config_id)
        
        return success(msg="翻译配置删除成功")
    except Exception as e:
        db.rollback()
        logger.error(f"删除翻译配置失败: {e}", exc_info=True)
        return fail(f"删除翻译配置失败: {str(e)}")

@router.post("/translation-configs/{config_id}/set-default", response_model=dict)
async def set_default_translation_config(
    config_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """设置默认翻译配置"""
    try:
        # 检查配置是否存在（可以是自己的或共享的）
        target_config = db.query(TranslationConfig).filter(
            TranslationConfig.id == config_id
        ).filter(
            (TranslationConfig.user_id == current_user.id) | (TranslationConfig.is_shared == True)
        ).first()
        
        if not target_config:
            return fail("配置不存在")
        
        # 更新用户的默认翻译配置ID
        user = db.query(User).filter(User.id == current_user.id).first()
        if user:
            user.default_translation_config_id = config_id
            db.commit()
        else:
            return fail("用户不存在")
        
        return success(msg="默认翻译配置设置成功")
    except Exception as e:
        db.rollback()
        logger.error(f"设置默认翻译配置失败: {e}", exc_info=True)
        return fail(f"设置默认翻译配置失败: {str(e)}")

@router.post("/translation-configs/{config_id}/toggle-share", response_model=dict)
async def toggle_translation_config_share(
    config_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """切换翻译配置的共享状态"""
    try:
        config = db.query(TranslationConfig).filter(
            TranslationConfig.id == config_id
        ).first()
        
        if not config:
            return fail("配置不存在")
        
        # 检查权限：只能操作自己的配置
        if config.user_id != current_user.id:
            return fail("无权操作他人的配置")
        
        new_share_status = not config.is_shared
        
        # 如果是取消共享，需要清除其他用户的默认配置关联
        if not new_share_status:
            db.query(User).filter(
                User.default_translation_config_id == config_id,
                User.id != current_user.id  # 仅清除其他用户的
            ).update({"default_translation_config_id": None})
            
        config.is_shared = new_share_status
        db.commit()
        db.refresh(config)
        
        status_text = "已共享" if config.is_shared else "已取消共享"
        return success(TranslationConfigResponse.from_orm(config), msg=f"翻译配置{status_text}")
    except Exception as e:
        db.rollback()
        logger.error(f"切换翻译配置共享状态失败: {e}", exc_info=True)
        return fail(f"操作失败: {str(e)}")

@router.post("/ai-models", response_model=dict)
async def get_ai_models(
    api_url: str = Query(..., description="AI API URL"),
    api_key: str = Query(..., description="AI API Key"),
    current_user: User = Depends(get_current_user)
):
    """
    获取AI模型列表
    根据提供的API URL和Key获取可用的模型列表
    """
    try:
        import requests
        
        # 处理URL：如果以#结尾则去掉#，否则添加/v1（如果没有）
        url = api_url.strip()
        if url.endswith('#'):
            base_url = url[:-1]
        elif url.endswith('/'):
            base_url = url.rstrip('/')
        elif url.endswith('/v1'):
            base_url = url
        else:
            base_url = f"{url}/v1"
        
        models_url = f"{base_url}/models"
        
        headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }
        
        response = requests.get(models_url, headers=headers, timeout=10)
        response.raise_for_status()
        result = response.json()
        
        # 提取模型ID列表
        if 'data' in result:
            models = [model['id'] for model in result['data']]
            return success(models)
        else:
            return fail("无法获取模型列表，API响应格式不正确")
            
    except requests.exceptions.Timeout:
        return fail("请求超时，请检查API URL是否正确")
    except requests.exceptions.ConnectionError:
        return fail("连接失败，请检查API URL是否可访问")
    except requests.exceptions.HTTPError as e:
        return fail(f"HTTP错误: {e.response.status_code}")
    except Exception as e:
        logger.error(f"获取AI模型列表失败: {e}", exc_info=True)
        return fail(f"获取模型列表失败: {str(e)}")